/*
        Updater For Java Programs 
        
    Copyright (C) 2010, Arttu Viljakainen 
    Published under GNU General Public License V3 
    (see http://www.gnu.org/licenses/licenses.html)
    
    This file is part of Updater For Java Programs.

    Updater For Java Programs is free software: 
    you can redistribute it and/or modify it under the terms of the GNU General 
    Public License as published by the Free Software Foundation, 
    either version 3 of the License, or (at your option) any later version.

    Updater For Java Programs is distributed in the hope that it will be useful, 
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General 
    Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Updater for Java programs. If not, see         
    <http://www.gnu.org/licenses/>.
 */
package checksum;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Hasher {

	private int blockSize = 8192;

	public boolean verifyFile(String checksum, File file) {

		return checksum.equals(getMD5HashFrom(file));

	}

	private String getMD5HashFrom(File file) {

		byte[] digest = null;

		try {
			digest = digestFile(file);
		} catch (NoSuchAlgorithmException nsae) {
			nsae.printStackTrace();
		} catch (FileNotFoundException fnfe) {
			fnfe.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}

		return getStringRepresentationOf(digest);
	}

	private byte[] digestFile(File file) throws NoSuchAlgorithmException, FileNotFoundException, IOException {

		MessageDigest md = MessageDigest.getInstance("MD5");
		InputStream is = new FileInputStream(file);
		try {
			is = new DigestInputStream(is, md);
			byte[] block = new byte[blockSize];
			while (is.read(block) != -1)
				;
		} finally {
			is.close();
		}

		return md.digest();

	}

	private String getStringRepresentationOf(byte[] digest) {

		String signature = new BigInteger(1, digest).toString(16);

		return signature;
	}

	public static void main(String[] args) {
		File file = new File("swan.zip");
		String hash = new MD5Hasher().getMD5HashFrom(file);
		System.out.println(hash);
	}

}
